package com.itheima.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SerializableUtils {

    /**
     * 序列化对象
     */
    public static<T> byte[] ser(T t) {

        ObjectOutput oos = null;
        ByteArrayOutputStream baos = null;
        try {
            //创建一个byte的数组的流
            baos = new ByteArrayOutputStream();
            //创建对象流将对象写入到byte数组里
            oos = new ObjectOutputStream(baos);
            //进行写入操作
            oos.writeObject(t);
            //将byte数组的对象进行转换为byte的数组
            return baos.toByteArray();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 反序列化对象
     */
    public static<T> T unser(byte[] bs) {
        ByteArrayInputStream bais = null;
        //创建一个byte的数组的读入流对其byte数组
        bais = new ByteArrayInputStream(bs);
        try {
            //对象的输入流，用于读取对象
            ObjectInputStream objectInputStream = new ObjectInputStream(bais);
            //将byte格式的转化为对象
            return (T)objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 序列化的List
     */
    public static<T> byte[] serList(List<T> list) {
        ObjectOutputStream oos = null;
        //
        ByteArrayOutputStream byteArrayOutputStream = null;
        byte[] bytes = null;
        byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            oos = new ObjectOutputStream(byteArrayOutputStream);
            for (T t : list) {
                oos.writeObject(t);

            }
            bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return bytes;
    }

    /**
     * 反序列化的List
     */
    public static<T> List<T> unserList(byte[] bytes) {
        List<T> list = new ArrayList<>();
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        bais = new ByteArrayInputStream(bytes);
        try {
            ois = new ObjectInputStream(bais);
            while (bais.available() > 0) {
                T t = (T)ois.readObject();
                if (t == null) {
                    break;

                }
                list.add(t);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }

}
